<template>
  <div class="app-container">
    <section>
      <div>
        <span
          style="font-size:20px;font-weight: bold; display:block;margin-bottom: 20px;text-align: center;"
        >
          退货出库订单
          <el-button size="mini" v-if="from.BillStatus==0" round>草稿</el-button>
          <el-button size="mini" v-if="from.BillStatus==1" round>已审核</el-button>
        </span>
      </div>
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form
          :inline="true"
          ref="from"
          :model="from"
          label-width="80px"
          class="demo-form-inline"
        >
          <div class="tabel">
            <el-form-item label="订单编号:">
              <span>{{from.OrderNo}}</span>
            </el-form-item>
            <el-form-item label="制单人:">
              <span>{{from.CreaterName}}</span>
            </el-form-item>
            <el-form-item label="制单时间:">
              <span>{{from.CreateDate}}</span>
            </el-form-item>
            <el-form-item label="摘要:">
              <el-input auto-complete="off" v-model="from.Summary" maxlength="12"></el-input>
            </el-form-item>
            <el-form-item label="仓库" prop="BranchId">
              <el-select v-model="from.BranchId" filterable placeholder="请选择到仓库">
                <el-option
                  v-for="item in StoreList"
                  :key="item.BranchId"
                  :label="item.BranchName"
                  :value="item.BranchId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="SupplierId">
              <el-select v-model="from.SupplierId" filterable placeholder="请选择供应商">
                <el-option
                  v-for="item in SupplierList"
                  :key="item.SupplierId"
                  :label="item.SupplierName"
                  :value="item.SupplierId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item>
            <el-button type="primary" @click="handleEdit()">新增商品</el-button>
            <el-button
              v-if="(this.$route.query.PRId || this.PRId) && from.BillStatus==0"
              type="success"
              @click="CheckPurchaseReturn()"
            >审核</el-button>
            <el-button v-if="from.BillStatus==0" type="primary" @click="UpdataAndAdd()">保存</el-button>
            <el-button v-if="from.BillStatus==1" type="danger" @click="UnCheckPurchaseReturn()">反审</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table
        :data="List"
        border
        :summary-method="getSummaries"
        show-summary
        height="600"
        :header-cell-style="{'background':'#F5F7FA','color':'#000',}"
      >
        <el-table-column prop="SKUName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
        <el-table-column prop="IsGift" label="赠品" align="center">
          <template slot-scope="scope">
            <el-checkbox @change="handlesum(scope.$index,scope.row)" v-model="scope.row.IsGift"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="Qty" label="退货数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              @change="handlesum(scope.$index,scope.row)"
              v-model="scope.row.Qty"
              size="mini"
              :min="0"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="SKUInPrice" label="进价" align="center">
          <template slot-scope="scope">
            <el-input-number
              @change="handlesum(scope.$index,scope.row)"
              v-model="scope.row.SKUInPrice"
              :precision="2"
              :step="0.1"
              :min="0"
              size="mini"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="TotalMoney" label="金额" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.TotalMoney.toFixed(2)|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.Remark" placeholder="请输入内容" maxlength="12"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑 -->
      <el-dialog title="商品列表" :visible.sync="editFormVisible" class="return-list">
        <el-form :inline="true">
          <el-form-item label="商品">
            <el-input v-model="from.PYCode" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getSkuList()" type="primary">查询</el-button>
            <el-button type="primary" @click.native="addSubmit()">确 定</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="skulist"
          height="480"
          ref="multipleTable"
          border
          style="width: 100%; margin-top: 20px"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
          :header-cell-style="{'background':'#F5F7FA','color':'#000',}"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column prop="ProductId" label="商品ID" align="center"></el-table-column>
          <el-table-column prop="SKUName" width="350" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
          <el-table-column prop="SKUInPrice" sortable label="进价" align="center"></el-table-column>
        </el-table>
        <el-pagination
          background
          layout=" prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
          style="float:right;margin-top: 10px;"
        ></el-pagination>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import {
  SKUList,
  Gett_cg_PurchaseReturnList,
  Gett_cg_PurchaseReturnDetailList,
  AddPurchaseReturn,
  GetPurchaseOrdersAdd,
  PurchaseGetSupplierList,
  UpPurchaseReturn,
  CheckPurchaseReturn,
  UnCheckPurchaseReturn
} from "@/api/api";
import Config from "../../api/config";
export default {
  data() {
    return {
      skulist: [],
      editFormVisible: false,
      page: 1,
      pageSize: 100,
      total: 0,
      PRId: "",
      from: {
        BranchId: 15,
        OrderNo: "",
        Creater: "",
        CreaterName: "",
        CreateDate: "",
        SupplierName: "",
        Summary: "",
        BillStatus: "",
        SupplierId: ""
      },
      tempList: [
        {
          ProductId: "",
          IsGift: "0",
          Unit: "",
          Qty: "",
          Price: "",
          Remark: ""
        }
      ],
      SupplierList: [],
      Id: "",
      List: [],
      StoreList: [
        {
          BranchId: 15,
          BranchName: "总仓"
        }
      ]
    };
  },
  filters: {
    numFilter(value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    }
  },
  created() {
    this.PRId = this.$route.query.PRId ? this.$route.query.PRId : "";
    this.getPurchaseOrders();
    this.PurchaseGetSupplierList();
  },
  methods: {
    handleAllSum() {
      var self = this;
      this.List.forEach(function(row, index) {
        console.log("输出row", row);
        console.log("index", index);
        self.handlesum(index, row);
      });
    },

    handlesum: function(index, row) {
      if (!row) return;
      if (row.IsGift == 1) {
        row.TotalMoney = 0;
      } else {
        row.TotalMoney = row.Qty * row.SKUInPrice;
      }

      this.List[index] = row;
      console.log(this.List);
    },
    //显示新增
    handleEdit: function() {
      this.editFormVisible = true;
      console.log(this.List);
      this.getSkuList();
    },
    //选择商品添加
    addSubmit() {
      var vdata = this.jsonspr;
      for (var j in vdata) {
        // vdata[j].Qty = 0;

        for (var i in this.List) {
          if (vdata[j].ProductId == this.List[i].ProductId) {
            vdata[j] = this.List[i];
          }
        }
      }
      this.List = vdata;
      console.log(this.List);
      this.handleAllSum();
      this.editFormVisible = false;
    },
    getRowKeys(row) {
      return row.ProductId;
    },
    //选择器
    handleSelectionChange(val) {
      console.log(val);
      this.jsonspr = val;
      this.handleAllSum();
    },

    getPurchaseOrders() {
      this.PRId = this.$route.query.PRId ? this.$route.query.PRId : this.PRId;
      if (this.PRId !== "") {
        this.Gett_cg_PurchaseReturnDetailList();
      } else {
        this.GetPurchaseOrdersAdd();
        return;
      }
    },

    //有值的时候为修改，无值的时候添加
    UpdataAndAdd() {
      this.PRId = this.$route.query.PRId ? this.$route.query.PRId : this.PRId;
      if (this.PRId !== "") {
        this.UpPurchaseReturn();
      } else {
        this.AddPurchaseReturn();
        return;
      }
    },

    //获取商品以及表头
    Gett_cg_PurchaseReturnDetailList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRId ? this.$route.query.PRId : this.PRId,
        Page: this.page,
        PageSize: this.pageSize
      };
      Gett_cg_PurchaseReturnDetailList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取退货出库单详情列表");
          console.log(vdata);
          self.List = vdata.DataList;
          self.List.forEach(el => {
            console.log("..............", el.IsGift);
            if (el.IsGift == 0) {
              el.IsGift = false;
            } else if (el.IsGift == 1) {
              el.IsGift = true;
            }
          });
          this.from.OrderNo = self.List[0].OrderNo;
          this.from.CreateDate = self.List[0].CreateDate.substr(0, 10);
          this.from.CreaterName = self.List[0].CreaterName;
          this.from.Summary = self.List[0].Summary;
          this.from.SupplierName = self.List[0].SupplierName;
          this.from.BillStatus = self.List[0].BillStatus;
          this.from.SupplierId = self.List[0].SupplierId;
          this.handleAllSum();
          console.log(this.from.BillStatus);
          console.log(this.PRId);
        }
      });
    },

    //审核采购订单
    CheckPurchaseReturn() {
      var self = this;
      self.tempList = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          IsGift: self.List[item].IsGift == "1" ? 1 : 0,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          Price: self.List[item].SKUInPrice,
          Remark: self.List[item].Remark
        };
        self.tempList.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        SupplierId: this.from.SupplierId,
        Summary: this.from.Summary,
        BranchId: this.from.BranchId,
        PRID: this.$route.query.PRId ? this.$route.query.PRId : this.PRId,
        tempList: self.tempList
      };
      UpPurchaseReturn(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
        }
      });
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRId ? this.$route.query.PRId : this.PRId
      };
      CheckPurchaseReturn(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.Gett_cg_PurchaseReturnDetailList();
        }
      });
    },

    //反审
    UnCheckPurchaseReturn() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRId ? this.$route.query.PRId : this.PRId
      };
      UnCheckPurchaseReturn(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.Gett_cg_PurchaseReturnDetailList();
        }
      });
    },

    //获取采购表头(新增时)
    GetPurchaseOrdersAdd() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Exter: "Ck"
      };
      GetPurchaseOrdersAdd(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取采购表头", vdata);
          this.from.OrderNo = vdata.OrderNo;
          this.from.CreateDate = vdata.dateTime.substr(0, 10);
          this.from.CreaterName = vdata.CreaterName;
          this.from.Creater = vdata.Creater;
        }
      });
    },

    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
    // toggleSelection(row) {
    //   console.log("执行选择", row);

    //   this.$refs.multipleTable.toggleRowSelection(row);
    // },
    //新增采购列表
    AddPurchaseReturn() {
      var self = this;
      self.tempList = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          IsGift: self.List[item].IsGift == "1" ? 1 : 0,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          Price: self.List[item].SKUInPrice,
          Remark: self.List[item].Remark,
          TotalMoney: self.List[item].SKUInPrice * self.List[item].Qty
        };
        self.tempList.push(a);
      }
      if (!this.from.SupplierId) {
        this.$message({
          message: "供应商不能为空",
          type: "error"
        });
        this.UpdataAndAddLoading = false;
        return;
      }

      if (self.tempList.length == 0) {
        this.$message({
          message: "商品不能为空",
          type: "error"
        });
        this.UpdataAndAddLoading = false;
        return;
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Creater: this.from.Creater,
        SupplierId: this.from.SupplierId,
        Summary: this.from.Summary,
        BranchId: this.from.BranchId,

        tempList: self.tempList
      };
      AddPurchaseReturn(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success",
            duration: 1000,
            onClose: () => {
              var vdata = JSON.parse(
                JSON.stringify(Base64.decode(res.data.Data))
              );
              console.log("获取商品列表", vdata);
              var list = vdata.DataList;
              self.skulist = list;
              // do something
              self.onGett_cg_PurchaseReturnList();
            }
          });
        }
      });
    },

    //获取验收入库单列表*
    onGett_cg_PurchaseReturnList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: 1,
        Status: -1,
        PageSize: 100,
        OrderNo: this.from.OrderNo
      };
      Gett_cg_PurchaseReturnList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          let vdata = JSON.parse(Base64.decode(res.data.Data));
          self.PRId = vdata.DataList[0].PRId;
          self.Gett_cg_PurchaseReturnDetailList();
        }
      });
    },

    //修改采购订单
    UpPurchaseReturn() {
      var self = this;
      self.tempList = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          IsGift: self.List[item].IsGift == "1" ? 1 : 0,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          Price: self.List[item].SKUInPrice,
          Remark: self.List[item].Remark
        };
        self.tempList.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        SupplierId: this.from.SupplierId,
        Summary: this.from.Summary,
        BranchId: this.from.BranchId,
        PRID: this.$route.query.PRId ? this.$route.query.PRId : this.PRId,
        tempList: self.tempList
      };
      UpPurchaseReturn(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          var vdata = JSON.parse(JSON.stringify(Base64.decode(res.data.Data)));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
        }
      });
    },

    //获取供应商列表
    PurchaseGetSupplierList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.page,
        PageSize: 20000
      };
      PurchaseGetSupplierList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取供应商列表", vdata);
          var list = vdata.DataList;
          self.SupplierList = list;
        }
      });
    },

    first1(rows) {
      this.$nextTick(() => {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      });
    },
    //获取商品列表
    getSkuList() {
      var self = this;
      console.log("输出选择项目", this.vdata);
      var para = {
        sessionid: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        page: this.page,
        pagesize: 100,
        PYCode: this.from.PYCode
      };
      var str = this.from.PYCode;
      console.log(str);
      if (/^[\u4e00-\u9fa5]+$/i.test(str)) {
        para.name = str;
        para.PYCode = " ";
      } else {
        para.name = " ";
      }
      SKUList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
          this.total = vdata.TotalCount;
          // this.wids = res.data.result.wids                 //点击详情接口返回的 table里被选中的行的wids
          let a = []; //    res.data.result.wids.split(',')          //分割成数组
          self.List.forEach(res => {
            //把表格里所有的id加入到b里
            a.push(res.ProductId.toString());
          });
          console.log("1", a);
          let b = [];
          self.skulist.forEach(res => {
            //把表格里所有的id加入到b里
            b.push(res.ProductId.toString());
          });
          console.log("0", b);
          // console.log(typeof(b[0]))
          for (let c = 0; c < b.length; c++) {
            //对b循环  如果b里面有a（a是被选中的行） 则把索引代入到first函数里 让这些行的复选框选中
            // console.log(b[c])
            // console.log(a.indexOf(b[c]))
            if (b.indexOf(a[c]) >= 0) {
              console.log(a.indexOf(b[c]));
              self.first1([self.skulist[b.indexOf(a[c])]]);
            }
          }
        }
      });
    },

    //求和
    getSummaries(param) {
      const { columns, data } = param;
      console.log("param", param);
      //console.log('data', data)
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index == 7) {
          sums[index] = 0;
          for (var item in data) {
            var row = data[item];
            if (row.IsGift == 1) {
              row.TotalMoney = 0;
            } else {
              row.TotalMoney = row.SKUInPrice * row.Qty;
            }
            sums[index] += data[item].zke;
          }
          sums[index] = sums[index].toFixed(2);
        }
        if (index == 5) {
          sums[index] = 0;
          for (var item in data) {
            sums[index] += data[item].TotalMoney;
          }
          sums[index] = sums[index].toFixed(2);
        }
        if (index == 3) {
          sums[index] = 0;
          for (var item in data) {
            sums[index] += data[item].Qty;
          }
          sums[index] = sums[index].toFixed(2);
        }
      });

      return sums;
    },
    //翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getSkuList();
    }
  }
};
</script>
<style scoped>
.tabel {
  display: inline-block;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 90%;
}
.tabel .el-form-item {
  width: 30%;
  /* letter-spacing:8px; */
}
.tabel .el-button {
  padding: 0 20px;
  height: 30px;
}
.el-form-item--medium .el-form-item__content,
.el-form-item--medium .el-form-item__label {
  color: black;
}
span {
  color: black;
}
</style>

<style lang="scss">
.return-list {
  .el-dialog {
    height: 700px;
  }
}
</style>